import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter1911/bean/cart_info_bean_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvider with ChangeNotifier {
  String? cartString = '[]'; //存到sp中的string
  List<CartInfoBeanResult> cartList = []; //从sp中读取到的list
  double allPrice = 0; //总价格
  num allGoodsCount = 0; //所有商品的总数量
  bool isAllCheck = true; //是否全选

  //存到sp中的方法
  save(goodsId, goodsName, count, price, images) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo'); //获取持久化数据
    print('取cartString:$cartString');
    //判断cartString是否为空,为空就说明是第一次添加,或者cartInfo被清除了
    //如果不为空,进行decode操作,也就是转换操作
    var tamp = cartString == null ? [] : json.decode(cartString.toString());
    //把获取到的值转换为list
    List<Map> tampList = (tamp as List).cast();
    //声明一个变量,用于判断购物车中是否已经存在此商品,通过id来判断
    var isHave = false;
    int ival = 0; //用于循环的int
    tampList.forEach((element) {
      //进行循环,找出是否已经存在的商品,如果存在,进行数量+1
      if (element['goodsId'] == goodsId) {
        tampList[ival]['count'] = element['count'] + 1;
        cartList[ival].count! + 1;
        isHave = true;
      }
      ival++;
    });

    if (!isHave) {
      Map<String, dynamic> newGood = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
        'isCheck': true //是否已经选择
      };
      tampList.add(newGood);
      cartList.add(CartInfoBeanResult.fromJson(newGood));
    }
    //把字符串进行encode
    cartString = json.encode(tampList).toString();
    print('存tampList:${tampList.toString()}');
    print('存cartString:$cartString}');
    print('存cartList:${cartList.toString()}');
    sharedPreferences.setString('cartInfo', cartString!);
  }

  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove('cartInfo');
    cartList.clear();
    print('sp清空完成');
    notifyListeners();
  }

  //得到购物车中所有商品的方法
  getCartInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    cartList = [];
    if (cartString == null) {
      cartList = [];
    } else {
      List<Map<String, dynamic>> tampList =
          (json.decode(cartString.toString()) as List).cast();
      allPrice = 0;
      allGoodsCount = 0;
      isAllCheck = true;
      tampList.forEach((element) {
        if (element['isCheck']) {
          allPrice += element['count'] * element['price'];
          allGoodsCount += element['count'];
        } else {
          isAllCheck = false;
        }
        cartList.add(CartInfoBeanResult.fromJson(element));
      });
    }
    notifyListeners();
  }

  //删除单个商品的方法
  deleteOneGoods(int goodsId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> teamList = (json.decode(cartString.toString()) as List).cast();

    int tempIndex = 0;
    int deleteIndex = 0;
    for (var element in teamList) {
      if (element['goodsId'] == goodsId) {
        deleteIndex = tempIndex;
      }
      tempIndex++;
    }
    teamList.remove(deleteIndex);
    cartString = json.encode(teamList).toString();
    sharedPreferences.setString('cartInfo', cartString!);
    await getCartInfo();
  }

  //修改选中状态
  changeCheckState(CartInfoBeanResult cartItem) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> teamList = (json.decode(cartString.toString()) as List).cast();
    int tempIndex = 0;
    int changeIndex = 0;

    for (var element in teamList) {
      if (element['goodsId'] == cartItem.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    }
    teamList[changeIndex] = cartItem.toJson(); //把对象转换成json对象
    cartString = json.encode(teamList).toString();
    sharedPreferences.setString('cartInfo', cartString!);
    await getCartInfo();
  }

  //点击徐安全按钮的操作
  changeAllCheckBtenState(bool isCheck) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    List<Map> newList = []; //用于组成新的持久化数据
    for (var item in tempList) {
      var newItem = item;
      newItem['isCheck'] = isCheck;
      newList.add(newItem);
    }
    cartString = json.encode(newList).toString();
    sharedPreferences.setString('cartInfo', cartString!);
    await getCartInfo();
  }
}
